﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;
using CCWin;
using Mes.仓库管理;
using Mes.仓库管理.WareHouse;
using Newtonsoft.Json;
using CCWin;                                    // CCWin皮肤控件库，提供现代化的UI外观
using Newtonsoft.Json;                          // JSON序列化和反序列化库
using Newtonsoft.Json.Linq;                     // JSON查询和操作库
using Mes.BOM管理.Model;                        // BOM管理相关的数据模型
using Mes.Production;                           // 生产管理相关的类
using Mes.质检管理;                             // 质检管理相关的类，用于加载质检管理页面
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Mes.BOM管理.Model;
using Mes.Production;
using Mes.Materials;
using Mes.采购管理;
using Mes.采购管理.model;
namespace Mes
{
    public partial class Menu : CCSkinMain
    {
        HttpClient httpClient = new HttpClient();
        private int Size = 15;
        private int Count = 0;
        private int Page = 0;
        private int CurrentPage = 1;
        private int TotalCount = 0;
        private int TotalPages = 0;
        
        private bool _createTimeFormatterHooked = false;
        private bool _deleteClickHooked = false;
        private AddProductionOrder _addProductionOrderForm; // 生产管理-新增生产订单窗体
        private ProductionOrderFrm _productionOrderForm; // 生产管理-生产订单列表窗体
        private Purchaseshow _purchaseshow; // 采购管理-显示采购订单窗体
        public Menu()
        {
            InitializeComponent();
            InitializeControls();
            InitializeBomPagination();
            LoadBomPageData();
            this.Purchase.Enter += Purchase_Enter;
            dataGridView1.CellContentClick += dataGridView1_CellContentClick;
        }
        private readonly HttpClient _httpClient = new HttpClient();
        private int PageSize = 5;
        private int TotalPage = 1;
        private int _currentPage = 1;
        private int _pageSize = 5;
        private int _totalPages = 1;
        //仓库
        private void InitializeControls()
        {
            // 设置DataGridView样式
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.ReadOnly = true;
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name="id",
                DataPropertyName = "Id",
                HeaderText = "ID",
                Visible=false
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "WarehouseNo",
                HeaderText = "仓库编号"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "WarehouseName",
                HeaderText = "仓库名称"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "WarehouseArea",
                HeaderText = "仓库区域"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "AddrNo",
                HeaderText = "位置编码"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "Area",
                HeaderText = "面积"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "HeadPeople",
                HeaderText = "负责人"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "States",
                HeaderText = "状态"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "Remark",
                HeaderText = "备注"
            });

            // 初始加载数据
            LoadDataAsync();
        }
        //仓库查询
        private void btnCha_Click_1(object sender, EventArgs e)
        {
            _currentPage = 1;
            LoadDataAsync();
        }
        //仓库上一页
        private void btnPrev_Click_1(object sender, EventArgs e)
        {
            if (_currentPage > 1)
            {
                _currentPage--;
                LoadDataAsync();
            }
        }
        //仓库下一页
        private void btnNext_Click_1(object sender, EventArgs e)
        {
            if (_currentPage < _totalPages)
            {
                _currentPage++;
                LoadDataAsync();
            }
        }
        private async void LoadDataAsync()
        {
            try
            {
                var queryParams = new StringBuilder();
                queryParams.Append($"Index={_currentPage}");
                queryParams.Append($"&Size={_pageSize}");

                if (!string.IsNullOrWhiteSpace(txtWareHouseNo1.Text))
                    queryParams.Append($"&WarehouseNo={txtWareHouseNo1.Text.Trim()}");

                if (!string.IsNullOrWhiteSpace(txtAddNo1.Text))
                    queryParams.Append($"&AddrNo={txtAddNo1.Text.Trim()}");

                string url = $"http://10.223.8.76:8085/api/WareHouse/ShowWareHouse?{queryParams}";
                string jsonResponse = await _httpClient.GetStringAsync(url);
                var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(jsonResponse);

                if (apiResponse?.Code == 200 && apiResponse.Data?.Data != null)
                {
                    _totalPages = apiResponse.Data.Page; // 假设后端返回了总页数
                                                         // 或者根据总记录数和每页记录数计算总页数
                                                         // _totalPages = (int)Math.Ceiling((double)apiResponse.Data.TotalCount / _pageSize);

                    lblPageInfo.Text = $"当前页: {_currentPage} / 总页数: {_totalPages}";

                    dataGridView1.DataSource = apiResponse.Data.Data;

                    UpdatePaginationButtons();
                }
                else
                {
                    MessageBox.Show($"数据加载失败: {apiResponse?.Message ?? "未知错误"}");
                }
                //修改
                if (!dataGridView1.Columns.Contains("btnEdit"))
                {
                    DataGridViewButtonColumn editColumn = new DataGridViewButtonColumn();
                    editColumn.Name = "btnEdit";
                    editColumn.HeaderText = "编辑";
                    editColumn.Text = "编辑";
                    editColumn.UseColumnTextForButtonValue = true;
                    dataGridView1.Columns.Add(editColumn);
                }

                // 添加“删除”按钮列
                if (!dataGridView1.Columns.Contains("btnDelete"))
                {
                    DataGridViewButtonColumn deleteColumn = new DataGridViewButtonColumn();
                    deleteColumn.Name = "btnDelete";
                    deleteColumn.HeaderText = "删除";
                    deleteColumn.Text = "删除";
                    deleteColumn.UseColumnTextForButtonValue = true;
                    dataGridView1.Columns.Add(deleteColumn);
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络错误: {ex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}");
            }

            this.Production.Enter += this.Production_Enter;

        }

        /// <summary>
        /// 调用删除的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == dataGridView1.Columns["btnEdit"].Index)
            {
                string materialId = dataGridView1.Rows[e.RowIndex].Cells["id"].Value?.ToString() ?? string.Empty;
                if (string.IsNullOrEmpty(materialId))
                {
                    MessageBox.Show("未获取到有效的 MaterialID");
                    return;
                }

                try
                {
                    WareHouseEdit editForm = new WareHouseEdit(materialId);
                    if (editForm.ShowDialog() == DialogResult.OK)
                    {
                        LoadDataAsync();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"编辑窗体初始化失败: {ex.Message}");
                }
            }
            else if (e.RowIndex >= 0 && e.ColumnIndex == dataGridView1.Columns["btnDelete"].Index)
            {
                string materialId = dataGridView1.Rows[e.RowIndex].Cells["id"].Value?.ToString() ?? string.Empty;
                if (!string.IsNullOrEmpty(materialId))
                {
                    await DeleteMaterial(materialId);
                }
            }
        }



        private async Task DeleteMaterial(string materialId)
        {
            try
            {
                // 1. 确认删除
                if (MessageBox.Show(
                    "确定要删除该仓库吗？",
                    "警告",
                    MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    return;
                }

                // 2. 调用删除接口（参数放在请求体中，而不是URL）
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://10.223.8.76:8085/");

                    // 构造请求体（如果后端要求）
                    var requestData = new
                    {
                        Id = materialId
                    };

                    string json = JsonConvert.SerializeObject(requestData);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 发送 PUT 请求
                    HttpResponseMessage response = await client.PostAsync(
                        "api/WareHouse/DeleteWareHouse",
                        content);

                    // 3. 处理响应
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("删除成功！");
                        LoadDataAsync(); // 刷新数据
                    }
                    else
                    {
                        string error = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"删除失败：{response.StatusCode}\n{error}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除失败：{ex.Message}");
            }
        }







        private void UpdatePageSize()
        {
            string selected = this.cboPageSize.Text;
            if (selected.Contains("15")) Size = 15;
            else if (selected.Contains("20")) Size = 20;
            else if (selected.Contains("50")) Size = 50;
            else if (selected.Contains("100")) Size = 100;
        }

        private void InitializeBomPagination()
        {
            // 初始化分页控件
            if (this.cboPageSize.Items.Count > 0)
            {
                this.cboPageSize.SelectedIndex = 0; // 默认选择15条/页
            }
            UpdatePageSize();
            CurrentPage = 1;
            TotalPage = 1;
            Count = 0;
            UpdatePaginationDisplay();
        }
		        //BOM列表显示
        private async void bto_search_Click(object sender, EventArgs e)
        {
            CurrentPage = 1; // 重置到第一页
            await LoadBomPageData();
        }
        //BOM列表显示
        private List<Product> TryExtractProducts(string json)
        {
            if (string.IsNullOrEmpty(json)) return new List<Product>();

            // 1) 按 ProductResponse
            try
            {
                var pr = JsonConvert.DeserializeObject<ProductResponse>(json);
                if (pr != null && pr.Products != null) return pr.Products;
            }
            catch { }

            // 2) 使用 JObject 容错：查找常见的承载位置（兼容大小写 Data/data）
            try
            {
                var jo = JObject.Parse(json);
                JToken arr = null;
                JToken dataNode = jo["Data"] ?? jo["data"]; // 顶层 Data 对象或数组
                if (dataNode != null)
                {
                    if (dataNode.Type == JTokenType.Array) arr = dataNode;
                    else arr = dataNode["Data"] ?? dataNode["data"]; // Data.Data 数组
                }
                if (arr == null)
                {
                    if (jo["products"] != null && jo["products"].Type == JTokenType.Array) arr = jo["products"];
                }
                if (arr != null)
                {
                    return arr.ToObject<List<Product>>();
                }
            }
            catch { }

            // 3) 直接数组
            try
            {
                return JsonConvert.DeserializeObject<List<Product>>(json);
            }
            catch { }

            return new List<Product>();
        }
        //BOM标题头
        private void ApplyBomGridHeaders()
        {
            if (this.dgv_BOMdata.Columns.Count == 0) return;
            // 重排顺序并设置标题
            if (this.dgv_BOMdata.Columns["Id"] != null)
            {
                this.dgv_BOMdata.Columns["Id"].HeaderText = "序号";
                this.dgv_BOMdata.Columns["Id"].DisplayIndex = 0;
                this.dgv_BOMdata.Columns["Id"].Visible = false;
            }
            if (this.dgv_BOMdata.Columns["Number"] != null)
            {
                this.dgv_BOMdata.Columns["Number"].HeaderText = "BOM编号";
                this.dgv_BOMdata.Columns["Number"].DisplayIndex = 1;
            }
            if (this.dgv_BOMdata.Columns["ProductNumber"] != null)
            {
                this.dgv_BOMdata.Columns["ProductNumber"].HeaderText = "成品编号";
                this.dgv_BOMdata.Columns["ProductNumber"].DisplayIndex = 2;
            }
            if (this.dgv_BOMdata.Columns["ProductName"] != null)
            {
                this.dgv_BOMdata.Columns["ProductName"].HeaderText = "成品名称";
                this.dgv_BOMdata.Columns["ProductName"].DisplayIndex = 3;
            }
            if (this.dgv_BOMdata.Columns["Model"] != null)
            {
                this.dgv_BOMdata.Columns["Model"].HeaderText = "规格型号";
                this.dgv_BOMdata.Columns["Model"].DisplayIndex = 4;
            }
            if (this.dgv_BOMdata.Columns["Size"] != null)
            {
                this.dgv_BOMdata.Columns["Size"].HeaderText = "尺寸";
                this.dgv_BOMdata.Columns["Size"].DisplayIndex = 5;
            }
            if (this.dgv_BOMdata.Columns["Operator"] != null)
            {
                this.dgv_BOMdata.Columns["Operator"].HeaderText = "操作人";
                this.dgv_BOMdata.Columns["Operator"].DisplayIndex = 6;
            }
            if (this.dgv_BOMdata.Columns["Version"] != null)
            {
                this.dgv_BOMdata.Columns["Version"].HeaderText = "BOM版本号";
                this.dgv_BOMdata.Columns["Version"].DisplayIndex = 7;
            }
            // CreateTime 列：中文标题与格式化
            if (this.dgv_BOMdata.Columns["CreateTime"] != null)
            {
                var col = this.dgv_BOMdata.Columns["CreateTime"];
                col.HeaderText = "添加时间";
                if (col.ValueType == typeof(DateTime) || col.ValueType == typeof(DateTime?))
                {
                    col.DefaultCellStyle.Format = "yyyy年MM月dd日 HH:mm:ss";
                }
                else if (!_createTimeFormatterHooked)
                {
                    this.dgv_BOMdata.CellFormatting += this.dgv_BOMdata_CellFormatting;
                    _createTimeFormatterHooked = true;
                }
            }

            // 删除按钮列
            if (this.dgv_BOMdata.Columns["Delete"] == null)
            {
                var btn = new DataGridViewButtonColumn();
                btn.Name = "Delete";
                btn.HeaderText = "操作";
                btn.Text = "删除";
                btn.UseColumnTextForButtonValue = true;
                btn.Width = 70;
                this.dgv_BOMdata.Columns.Add(btn);
            }
            this.dgv_BOMdata.Columns["Delete"].DisplayIndex = this.dgv_BOMdata.Columns.Count - 1;
            if (!_deleteClickHooked)
            {
                this.dgv_BOMdata.CellContentClick += this.dgv_BOMdata_CellContentClick;
                _deleteClickHooked = true;
            }
        }
        private void UpdatePaginationButtons()
        {
            btnPrev.Enabled = (CurrentPage > 1);
            btnNext.Enabled = (CurrentPage<TotalPage);
        }
        //BOM格式化时间
        private void dgv_BOMdata_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex < 0) return;
            var grid = this.dgv_BOMdata;
            if (grid.Columns[e.ColumnIndex].Name == "CreateTime" && e.Value != null)
            {
                DateTime dt;
                if (e.Value is DateTime)
                {
                    dt = (DateTime)e.Value;
                    e.Value = dt.ToString("yyyy年MM月dd日 HH:mm:ss");
                    e.FormattingApplied = true;
                }
                else
                {
                    if (DateTime.TryParse(e.Value.ToString(), out dt))
                    {
                        e.Value = dt.ToString("yyyy年MM月dd日 HH:mm:ss");
                        e.FormattingApplied = true;
                    }
                }
            }
        }
        //BOM删除
        private async void dgv_BOMdata_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            if (this.dgv_BOMdata.Columns[e.ColumnIndex].Name != "Delete") return;
            var item = this.dgv_BOMdata.Rows[e.RowIndex].DataBoundItem as Product;
            if (item == null) return;
            if (MessageBox.Show("确认删除该BOM？", "确认", MessageBoxButtons.YesNo) != DialogResult.Yes) return;
            try
            {
                string baseUrl = "http://10.223.8.10:8000/BOM/api/BOM/BOMDelete";
                string url = baseUrl + "?id=" + item.Id;
                // 优先尝试 { id }
                var payload1 = new StringContent(JsonConvert.SerializeObject(new { id = item.Id }), Encoding.UTF8, "application/json");
                string body = await HttpClientHelper.ClientAsync("POST", url, isAuthorzation: !string.IsNullOrEmpty(login.CurrentToken), content: payload1);
                // 如果后端提示需要 command，则再试一次
                if (!string.IsNullOrEmpty(body) && body.IndexOf("command", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    var payload2 = new StringContent(JsonConvert.SerializeObject(new { command = new { id = item.Id } }), Encoding.UTF8, "application/json");
                    body = await HttpClientHelper.ClientAsync("POST", url, isAuthorzation: !string.IsNullOrEmpty(login.CurrentToken), content: payload2);
                }

                // 简单判断是否成功（可按后端返回结构完善）
                if (string.IsNullOrEmpty(body))
                {
                    MessageBox.Show("删除失败: 未返回内容");
                    return;
                }

                var list = this.dgv_BOMdata.DataSource as List<Product>;
                if (list != null)
                {
                    for (int i = list.Count - 1; i >= 0; i--)
                    {
                        if (list[i].Id == item.Id) list.RemoveAt(i);
                    }
                    this.dgv_BOMdata.DataSource = null;
                    this.dgv_BOMdata.DataSource = list;
                    ApplyBomGridHeaders();
                }
                else
                {
                    this.dgv_BOMdata.Rows.RemoveAt(e.RowIndex);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除异常: " + ex.Message);
            }
        }
        //BOM自动加载
        /// <summary>
        /// 标签页切换事件处理
        /// 根据用户选择的标签页执行相应的操作
        /// </summary>
        /// <param name="sender">事件源对象</param>
        /// <param name="e">事件参数</param>
        private async void skinTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 根据选中的标签页执行不同的操作
            if (skinTabControl1.SelectedTab == this.BOM)
            {
                // 如果选择BOM管理标签页，执行BOM数据查询
                CurrentPage = 1;
                await LoadBomPageData();
            }
            else if (skinTabControl1.SelectedTab == this.Check)
            {
                // 如果选择质检管理标签页，加载质检管理导航页面
                LoadQualityInspectionPage();
            }
            else if (skinTabControl1.SelectedTab == this.Production)
            {
                // 如果选择生产管理标签页，加载生产订单管理页面
                LoadProductionOrderPage();
            }
            // 注意：可以在这里添加其他标签页的处理逻辑
            // 例如：else if (skinTabControl1.SelectedTab == this.WareHouse) { LoadWarehousePage(); }
        }

        /// <summary>
        /// 加载质检管理页面
        /// 将Chencknavigation页面嵌入到质检管理标签页中
        /// </summary>
        private void LoadQualityInspectionPage()
        {
            
            
                // 第一步：清空质检管理标签页的现有控件
                // 确保标签页是干净的，避免控件重叠
                this.Check.Controls.Clear();

                // 第二步：创建质检导航页面实例
                // Chencknavigation是质检管理的主导航页面
                var chenckNavigationForm = new 质检管理.Chencknavigation();

                // 第三步：设置窗体属性，使其能够嵌入到标签页中
                chenckNavigationForm.TopLevel = false;           // 设置为非顶级窗体，可以嵌入到其他容器中
                chenckNavigationForm.FormBorderStyle = FormBorderStyle.None;  // 移除窗体边框，实现无缝嵌入
                chenckNavigationForm.Dock = DockStyle.Fill;      // 设置停靠方式为填充，占满整个标签页区域

                // 第四步：将质检导航页面添加到质检管理标签页
                // 这样用户就能在标签页中看到质检管理的完整界面
                this.Check.Controls.Add(chenckNavigationForm);

                // 第五步：显示窗体
                chenckNavigationForm.Show();
            
           
        }
        //添加
        private async void btn_BOMcreate_Click(object sender, EventArgs e)
        {
            using (var create = new BOMCreate())
            {
                var result = create.ShowDialog();
                if (result == DialogResult.OK)
                {
                    this.skinTabControl1.SelectedTab = this.BOM;
                    CurrentPage = 1;
                    await LoadBomPageData();
                }
            }
        }
        /// <summary>
        /// 加载生产订单管理页面
        /// 将ProductionOrderFrm页面嵌入到生产管理标签页中
        /// </summary>
        private void LoadProductionOrderPage()
        {
            try
            {
                // 第一步：清空生产管理标签页的现有控件
                // 确保标签页是干净的，避免控件重叠
                this.Production.Controls.Clear();

                // 第二步：创建生产订单管理页面实例
                // ProductionOrderFrm是生产管理的主页面
                if (_productionOrderForm == null || _productionOrderForm.IsDisposed)
                {
                    _productionOrderForm = new ProductionOrderFrm();
                }

                // 第三步：设置窗体属性，使其能够嵌入到标签页中
                _productionOrderForm.TopLevel = false;           // 设置为非顶级窗体，可以嵌入到其他容器中
                _productionOrderForm.FormBorderStyle = FormBorderStyle.None;  // 移除窗体边框，实现无缝嵌入
                _productionOrderForm.Dock = DockStyle.Fill;      // 设置停靠方式为填充，占满整个标签页区域

                // 第四步：将生产订单管理页面添加到生产管理标签页
                // 这样用户就能在标签页中看到生产管理的完整界面
                this.Production.Controls.Add(_productionOrderForm);

                // 第五步：显示窗体
                _productionOrderForm.Show();
            }
            catch (Exception ex)
            {
                // 异常处理：如果加载失败，显示友好的错误提示
                MessageBox.Show("加载生产订单管理页面失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //生产管理
        private void Production_Enter(object sender, EventArgs e)
        {
            // 当用户进入生产管理标签页时，加载生产订单管理页面
            LoadProductionOrderPage();
        }
        //重置
        private async void skinButton1_Click(object sender, EventArgs e)
        {
            txtProductNumber.Text = null;
            txtProductName.Text = null;
            CurrentPage = 1;
            await LoadBomPageData();
        }

        // BOM分页相关方法
        private void ExtractPaginationInfo(string json)
        {
            try
            {
                var jo = JObject.Parse(json);
                JToken dataNode = jo["Data"] ?? jo["data"];
                if (dataNode != null)
                {
                    if (dataNode["TotalCount"] != null) Count = (int)dataNode["TotalCount"];
                    if (dataNode["TotalPage"] != null) TotalPage = (int)dataNode["TotalPage"];
                }
            }
            catch { }
        }

        private void UpdatePaginationDisplay()
        {
            this.lblPageInfo.Text = string.Format("共 {0} 条记录，第 {1}/{2} 页", Count, CurrentPage, TotalPage);
            this.btnPrevPage.Enabled = CurrentPage > 1;
            this.btnNextPage.Enabled = CurrentPage < TotalPage;
            this.btnFirstPage.Enabled = CurrentPage > 1;
            this.btnLastPage.Enabled = CurrentPage < TotalPage;
            this.txtGoToPage.Text = CurrentPage.ToString();
        }

        // BOM分页事件处理
        private async void btnPrevPage_Click(object sender, EventArgs e)
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                await LoadBomPageData();
            }
        }

        private async void btnNextPage_Click(object sender, EventArgs e)
        {
            if (CurrentPage < TotalPage)
            {
                CurrentPage++;
                await LoadBomPageData();
            }
        }

        private async void btnFirstPage_Click(object sender, EventArgs e)
        {
            if (CurrentPage != 1)
            {
                CurrentPage = 1;
                await LoadBomPageData();
            }
        }

        private async void btnLastPage_Click(object sender, EventArgs e)
        {
            if (TotalPage > 0 && CurrentPage != TotalPage)
            {
                CurrentPage = TotalPage;
                await LoadBomPageData();
            }
        }

        private async void btnGoToPage_Click(object sender, EventArgs e)
        {
            int targetPage;
            if (int.TryParse(this.txtGoToPage.Text, out targetPage) && targetPage >= 1 && targetPage <= TotalPage)
            {
                CurrentPage = targetPage;
                await LoadBomPageData();
            }
            else
            {
                MessageBox.Show("请输入有效的页码");
                this.txtGoToPage.Text = CurrentPage.ToString();
            }
        }

        private async void cboPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdatePageSize();
            CurrentPage = 1;
            await LoadBomPageData();
        }
        //BOM显示
        private async Task LoadBomPageData()
        {
            string baseUrl = "http://10.223.8.10:8000/BOM/api/BOM/ProductShow";
            var sb = new StringBuilder();
            sb.Append(baseUrl).Append("?index=").Append(CurrentPage).Append("&size=").Append(Size);
            if (!string.IsNullOrEmpty(this.txtProductNumber.Text))
            {
                sb.Append("&productNumber=").Append(Uri.EscapeDataString(this.txtProductNumber.Text));
            }
            if (!string.IsNullOrEmpty(this.txtProductName.Text))
            {
                sb.Append("&productName=").Append(Uri.EscapeDataString(this.txtProductName.Text));
            }
            string fullUrl = sb.ToString();

            // 使用 HttpClientHelper 进行 GET 请求，自动带上授权头（若有）
            string json = await HttpClientHelper.ClientAsync("GET", fullUrl, isAuthorzation: !string.IsNullOrEmpty(login.CurrentToken));

            List<Product> products = TryExtractProducts(json);
            ExtractPaginationInfo(json);
            this.dgv_BOMdata.DataSource = products ?? new List<Product>();
            ApplyBomGridHeaders();
            UpdatePaginationDisplay();
        }
        //BOM导出
        private async void skinButtonExport_Click(object sender, EventArgs e)
        {
            try
            {
                string baseUrl = "http://10.223.8.10:8000/BOM/api/BOM/DownExcel";
                var sb = new StringBuilder();
                sb.Append(baseUrl).Append("?index=").Append(CurrentPage).Append("&size=").Append(Size);
                if (!string.IsNullOrEmpty(this.txtProductNumber.Text))
                {
                    sb.Append("&productNumber=").Append(Uri.EscapeDataString(this.txtProductNumber.Text));
                }
                if (!string.IsNullOrEmpty(this.txtProductName.Text))
                {
                    sb.Append("&productName=").Append(Uri.EscapeDataString(this.txtProductName.Text));
                }
                string url = sb.ToString();

                var bytes = await HttpClientHelper.GetBytesAsync(url, isAuthorzation: !string.IsNullOrEmpty(login.CurrentToken));
                if (bytes == null || bytes.Length == 0)
                {
                    MessageBox.Show("导出失败：未获取到文件内容");
                    return;
                }
                using (var sfd = new SaveFileDialog())
                {
                    sfd.Filter = "Excel 文件 (*.xlsx)|*.xlsx|Excel 旧格式 (*.xls)|*.xls|所有文件 (*.*)|*.*";
                    sfd.FileName = "BOM物料清单.xlsx";
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        File.WriteAllBytes(sfd.FileName, bytes);
                        MessageBox.Show("导出成功：" + sfd.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出异常: " + ex.Message);
            }
        }
        private void Purchase_Enter(object sender, EventArgs e)
        {
            try
            {
                if (_purchaseshow == null || _purchaseshow.IsDisposed)
                {
                    _purchaseshow = new Purchaseshow();
                    _purchaseshow.TopLevel = false;
                    _purchaseshow.FormBorderStyle = FormBorderStyle.None;
                    _purchaseshow.Dock = DockStyle.Fill;
                }

                if (_purchaseshow.Parent != this.Production)
                {
                    this.Purchase.Controls.Clear();
                    this.Purchase.Controls.Add(_purchaseshow);
                }

                _purchaseshow.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载采购订单失败: " + ex.Message);
            }
        }

        // 仓库添加
        private void btnAddWareHouse_Click_1(object sender, EventArgs e)
        {
            WareHouseCreate add = new WareHouseCreate();
            add.Show();
        }
        // 仓库刷新
        private void btnnew_Click(object sender, EventArgs e)
        {
            txtWareHouseNo1.Text = null;
            txtAddNo1.Text = null;
            LoadDataAsync();
        }
        //添加
        private async void skinButton2_Click(object sender, EventArgs e)
        {
            using (var bomcreate = new BOMCreate())
            {
                var result = bomcreate.ShowDialog();
                if (result == DialogResult.OK)
                {
                    this.skinTabControl1.SelectedTab = this.BOM;
                    CurrentPage = 1;
                    await LoadBomPageData();
                }
            }
        }

        private void Materials_Click(object sender, EventArgs e)
        {
            // 清除 Panel 中的现有内容
            panelContainer.Controls.Clear();
            // 创建独立窗体实例
            MaterialsForm rawMaterialForm = new MaterialsForm();
            rawMaterialForm.TopLevel = false; // 确保设置为非顶级窗口
            rawMaterialForm.FormBorderStyle = FormBorderStyle.None; // 可选：隐藏边框
            rawMaterialForm.Dock = DockStyle.Fill; // 可选：填充整个 Panel
            rawMaterialForm.Visible = true;
            // 将独立窗体添加到 Panel 中
            panelContainer.Controls.Add(rawMaterialForm);
            // 显示独立窗体
            rawMaterialForm.Show();

            Console.WriteLine($"Panel 中控件数量: {panelContainer.Controls.Count}");
            if (panelContainer.Controls.Contains(rawMaterialForm))
            {
                Console.WriteLine("MaterialsForm 已成功添加到 Panel");
            }
            else
            {
                Console.WriteLine("MaterialsForm 未添加到 Panel");
            }
        }
    }
}

